/*

 atomic-hijax
 Copyright (C) 2013 - Alistair Garrison
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

*/

// Function gF gets html fragment from server

function gF(url, tId, data) {
	var rq = new XMLHttpRequest();
    var method = "GET";
    if (data != null) {
        method = "POST";
    }
	rq.open(method, url, true);
	rq.onreadystatechange = statusListener;
    if (data != null) {
        rq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    }
	rq.send(data);
	
	function statusListener() {
		if (rq.readyState == 4) {
            var status = rq.status;
			if ((status == 200)||(status == 304)) {
				var tE = document.querySelector("#" + tId);
                tE.innerHTML = rq.responseText;
			}
		}
	}
}

var hE = document.querySelectorAll("[data-ahu][data-aht]"); // Hijax Elements
for (var i = hE.length; i--;) {
    var el = hE[i];
    var tN = el.tagName; // tagName
    var aO = el.getAttribute("data-aht");
    var tE = document.querySelector("#" + aO); // target Element
    if (tE) {
        tE.setAttribute("role", "region");
        tE.setAttribute("aria-live", "polite");
        if (tN == "A") {
            var cA = function(e) {
                // click handler for A elements
                e.preventDefault();
                var tr = e.target; 
                gF(tr.getAttribute("data-ahu"), tr.getAttribute("data-aht"), null);
            }
            el.addEventListener("click", cA, false);
        }
        if (tN == "FORM") {
            var sF = function(e) {
                // submit handler for FORM elements
                e.preventDefault();
                var tr = e.target;
                var cD = function() {
                    var da = ""; // da is data
                    var fE = tr.elements; // form elements
                    for (var i = fE.length;i--;) {
                        var fo = fE[i]; // fo = form element
                        var na = fo.name;
                        var va = fo.value;
                        if (na && va) {
                            da+=na + "=";
                            da+=escape(va) + "&";
                        }
                    }
                    return da;
                }
                gF(tr.getAttribute("data-ahu"), tr.getAttribute("data-aht"), cD());
            }
            el.addEventListener("submit", sF, false);
        }
    }
}
